<!--
 * @Description:
 * @Author: Ambrose
 * @Date: 2022-01-18 15:43:06
 * @LastEditTime: 2024-06-23 17:40:52
 * @LastEditors: Ambrose
-->
<template>
  <el-card>
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input
          :placeholder="$t('table.placeholder')"
          clearable
          v-model="queryForm.query"
        ></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="handleSearch"
        >查询</el-button
      >
      <el-button type="primary" @click="handleDialogValue({})"
        >添加客户</el-button
      >
      <el-button type="primary" @click="handleExportToCSV"
        >导出成CSV文件</el-button
      >
    </el-row>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        :width="item.width"
        :prop="item.prop"
        :label="item.label"
        v-for="(item, index) in options"
        :key="index"
      >
        <template #default="{ row }" v-if="item.prop === 'action'">
          <el-button
            type="primary"
            size="small"
            :icon="Edit"
            @click="handleDialogValue(row)"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="del(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="queryForm.pageNum"
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
  <Dialog
    v-model="dialogVisible"
    :dialogTitle="dialogTitle"
    v-if="dialogVisible"
    @init="init"
    :dialogTableValue="dialogTableValue"
  />
</template>

<script setup>
import { Search, Edit, Delete } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { options } from './options'
import axios from 'axios'
import Dialog from './components/dialog.vue'
import { isNull } from '@/utils/filters'
import { ElMessage, ElMessageBox } from 'element-plus'

const queryForm = ref({
  query: '',
  pageNum: 1,
  pageSize: 10
})

const tableData = ref([])
const total = ref({})
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogTableValue = ref({})

const handleExportToCSV = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8090/producer/export', {
      responseType: 'blob' // 设置响应类型为 blob
    })

    if (response.status === 200) {
      const blob = new Blob([response.data], { type: 'text/csv' })
      const downloadLink = document.createElement('a')
      downloadLink.href = URL.createObjectURL(blob)
      downloadLink.download = 'producer.csv'
      downloadLink.click()
    } else {
      // 处理导出失败的情况
      console.log('导出失败')
    }
  } catch (error) {
    // 处理异常
    console.error('导出过程中发生错误:', error)
  }
}

const init = async () => {
  const { query, pageNum, pageSize } = queryForm.value
  const params = {
    query: query,
    pageNum: pageNum,
    pageSize: pageSize
  }
  const res = await axios.get('http://127.0.0.1:8090/producer', {
    params: params
  })
  tableData.value = res.data.data.records
  total.value = res.data.data.total
}

init()

const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1
  queryForm.value.pageSize = pageSize
  init()
}

const handleCurrentChange = (pageNum) => {
  queryForm.value.pageNum = pageNum
  init()
}

const handleSearch = () => {
  init()
}
const handleDialogValue = (row) => {
  if (isNull(row)) {
    dialogTitle.value = '添加客户'
    dialogTableValue.value = {}
  } else {
    dialogTitle.value = '编辑客户'
    dialogTableValue.value = JSON.parse(JSON.stringify(row))
  }
  dialogVisible.value = true
}

const del = (row) => {
  ElMessageBox.confirm('该操作将会删除该条数据，确认?', 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await axios.delete('http://127.0.0.1:8090/producer', {
        params: {
          id: row.id
        }
      })
      if (res.data.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        init()
      } else {
        ElMessage.error(res.data.msg)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消'
      })
    })
}
</script>

<style lang="scss" scoped>
.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}

::v-deep .el-input__suffix {
  align-items: center;
}
</style>
